<template>
	<div>
		<!-- vant 输入框 -->
		<van-search shape="round" v-model.trim="value" placeholder="请输入搜索关键词" @clear="clearFn" @input="inputFn" />

		<!-- 搜索下容器 -->
		<div v-if="resArr.length === 0" class="search_wrap">
			<p class="hot_title">热门搜索</p>
			<div class="hot_name_wrap">
				<!-- 每个搜索关键词 -->
				<span v-for="(item, index) in hotArr" :key="index" class="hot_item" @click="clickFn(item.first)">
					{{ item.first }}
				</span>
			</div>
		</div>

		<!-- 搜索结果 -->
		<div v-else class="search_wrap">
			<!-- 标题 -->
			<p class="hot_title">最佳匹配</p>

			<van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">


				<SongItem v-for="item in resArr" :key="item.id" :title="item.name" :label="item.ar[0].name" :id="item.id">
				</SongItem>
			</van-list>
		</div>
	</div>
</template>
<script>
import SongItem from '@/components/SongItem.vue'
import { hotSearchList, getSearchRes } from '@/api'


async function fn() {
	return 1
}
console.log(fn())

export default {
	data() {
		return {
			value: '', // 输入框
			hotArr: [], // 热搜关键字列表 数据
			resArr: [], // 搜索结果 数据
			loading: false, // 表示是否正在加载更多数据，默认为false，表示未正在加载
			finished: false, // 表示是否所有的数据都加载结束了，默认为false，表示没有结束
			page: 1, // 页数，默认为1，默认展示第一页数据
		}
	},
	components: {
		SongItem,
	},
	async created() {
		const { data: res } = await hotSearchList()
		console.log(res)
		this.hotArr = res.result.hots
	},
	methods: {
		async inputFn() {

			if (this.value === '') return


			this.page = 1
			this.finished = false

			const res = await this.getResFn()
			console.log(res)


			if (res.result.songs === undefined) {

				this.resArr = []
				return
			}


			this.resArr = res.result.songs
		},
		async onLoad() {
			console.log('列表滚动到底部，会触发load事件')

			this.page++
			const res = await this.getResFn()
			console.log(res)


			if (res.result.songs === undefined) {
				this.finished = true

				this.loading = false

				return
			}

			this.resArr = [...this.resArr, ...res.result.songs]
			this.loading = false
		},
		clearFn() {
			this.resArr = []
		},
		async clickFn(val) {
			this.value = val

			this.page = 1
			this.finished = false

			const res = await this.getResFn()
			console.log(res)

			this.resArr = res.result.songs
		},

		async getResFn() {

			const { data: res } = await getSearchRes({

				keywords: this.value,
				limit: 50,
				offset: (this.page - 1) * 50,
			})

			return res
		},
	},
}
</script>

<style scoped>
/* 搜索容器的样式 */
.search_wrap {
	padding: 0.266667rem;
}

/*热门搜索文字标题样式 */
.hot_title {
	font-size: 0.32rem;
	color: #666;
}

/* 热搜词_容器 */
.hot_name_wrap {
	margin: 0.266667rem 0;
}

/* 热搜词_样式 */
.hot_item {
	display: inline-block;
	height: 0.853333rem;
	margin-right: 0.213333rem;
	margin-bottom: 0.213333rem;
	padding: 0 0.373333rem;
	font-size: 0.373333rem;
	line-height: 0.853333rem;
	color: #333;
	border-color: #d3d4da;
	border-radius: 0.853333rem;
	border: 1px solid #d3d4da;
}
</style>
